import json
def show_books(book_list):
	''' 展示图书 '''
	# 如果书已经存在
	if book_list:
		for book in book_list:
			print("书名: %(name)s, 作者: %(author)s, 页数:%(page)d" % book)
	# 不存在此书
	else:
		print("====找不到这本书！====")

def add_books(book_list):
	''' 添加书 '''
	name = input("请输入书名: \n")
	author = input("请输入作者名: \n")
	r = has_book(name, book_list)
	# 如果不存在书
	if r is None:
		book_dict = {}
		book_dict['name'] = name
		book_dict['author'] = author
		book_dict['page'] = int(input("请输入页数:\n"))
		book_dict['count'] = 1
		book_list.append(book_dict)
		saue_book(book_list)
	else:
		book_dict = book_list[r]
		book_dict['count'] += 1
		saue_book(book_list)
	
def saue_book(book_list):
	with open("books.txt", 'w', encoding="utf-8") as f:
		json.dump(book_list, f)


def has_book(name, book_list):
	''' 判断是否有这本书 '''
	for index in range(len(book_list)):
		# 取书
		book = book_list[index]
		if book['name'] == name:
			return index
	return None

def sell_book(book_list):
	''' 删除书 '''
	name = input("删除书: \n")
	r = has_book(name, book_list)
	if r is None:
		print("%s 该书已下架!" % (name))
	else:
		book_dict = book_list[r]
		book_dict['count'] -= 1
		print("成功删除%(name)s, 页数%(page)d" % book_dict)
		# 如果没有这本书
		if book_dict['count'] == 0:
			# 从书列表中删除该书
			book_list.pop(r)
			print("%s已经没有这本书了" % (name))

def search_book(book_list):
	''' 搜索书 '''
	name = input('请输入您需要的书名：')
	# 取出符合条件的所有书
	f = lambda book: book['name'] == name
	r_list = list(filter(f, book_list))
	if r_list:
		print("===您要的书===")
		show_books(r_list)
	else:
		print("没有找到这本书！")